package com.ruoyi.business.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.business.service.ClassPermissionsService;
import com.ruoyi.business.service.IWsdLeaveTypesService;
import com.ruoyi.business.service.IWsdLeavesService;
import com.ruoyi.business.service.IWsdMealRefundsService;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.dto.LeaveSummaryDTO;
import com.ruoyi.common.core.domain.dto.leaveStatisticsDTO;
import com.ruoyi.common.core.domain.dto.wsdLeavesDTO;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.entity.WsdLeaveTypes;
import com.ruoyi.common.core.domain.entity.WsdLeaves;
import com.ruoyi.common.core.domain.entity.WsdMealRefunds;
import com.ruoyi.common.core.domain.vo.LeaveStatsVO;
import com.ruoyi.common.core.domain.vo.LeaveSummaryVO;
import com.ruoyi.common.core.domain.vo.leaveStatisticsVO;
import com.ruoyi.common.core.domain.vo.wsdLeavesVO;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.date.DateTimeUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.IsoFields;

import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 请假Controller
 *
 * @author ruoyi
 * @date 2024-04-16
 */
@RestController
@RequestMapping("/wsd_leaves")
public class WsdLeavesController extends BaseController {

    @Autowired
    private IWsdLeavesService wsdLeavesService;
    @Autowired
    private IWsdLeaveTypesService wsdLeaveTypesService;
    @Autowired
    private IWsdMealRefundsService wsdMealRefundsService;
    @Autowired
    private ClassPermissionsService classPermissionsService;
    /**
     * 查询请假列表111
     */
    @PreAuthorize("@ss.hasPermi('business:leaves:list')")
    @GetMapping("/list")
    public TableDataInfo list(wsdLeavesDTO wsdLeavesDTO) {
        SysUser user = getLoginUser().getUser();
        if (user.getSchoolId()==null){
            List<wsdLeavesVO> leavesVOS = new ArrayList<>();
            return getDataTable(leavesVOS);
        }
        Long schoolId = user.getSchoolId();
        if (!user.isAdmin()) {
            wsdLeavesDTO.setSchoolId(schoolId);
            //班级权限 过滤掉学校管理员和admin
            if (!"business".equals( user.getRoles().get( 0 ).getRoleKey() )) {
                String classIds = classPermissionsService.classIds();
                wsdLeavesDTO.setClassIds( classIds );
            }
        }
        startPage();
        List<wsdLeavesVO> list = wsdLeavesService.selectWsdLeavesList(wsdLeavesDTO);
        return getDataTable(list);
    }

    /**
     * 导出请假列表
     */
    @PreAuthorize("@ss.hasPermi('business:leaves:export')")
    @Log(title = "请假", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, wsdLeavesDTO wsdLeavesDTO)
    {
        List<wsdLeavesVO> list = wsdLeavesService.selectWsdLeavesList(wsdLeavesDTO);
        ExcelUtil<wsdLeavesVO> util = new ExcelUtil<wsdLeavesVO>(wsdLeavesVO.class);
        util.exportExcel(response, list, "请假数据");
    }

    /**
     * 获取请假详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:leaves:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        WsdLeaves wsdLeaves = wsdLeavesService.getById(id);
        WsdLeaveTypes wsdLeaveTypes = wsdLeaveTypesService.getById(wsdLeaves.getLeaveTypeId());
        wsdLeaves.setTypeName(wsdLeaveTypes.getTypeName());
        return success(wsdLeaves);
    }



    /**
     * 修改请假
     */
    @PreAuthorize("@ss.hasPermi('business:leaves:edit')")
    @Log(title = "请假", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WsdLeaves wsdLeaves) {
        return toAjax(wsdLeavesService.updateWsdLeaves(wsdLeaves));
    }

    /**
     * 删除请假
     */
    @PreAuthorize("@ss.hasPermi('business:leaves:remove')")
    @Log(title = "请假", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        for (Long id : ids){
            //改为不同意退款
            LambdaUpdateWrapper<WsdMealRefunds> wrapper1 = new LambdaUpdateWrapper<>();
            wrapper1.eq(WsdMealRefunds::getLeaveId,id);
            wrapper1.set(WsdMealRefunds::getStatus,-1);
            wsdMealRefundsService.update(wrapper1);
        }
        return toAjax(wsdLeavesService.deleteWsdLeavesByIds(ids));
    }


    /**
     * 请假统计
     */
    @PreAuthorize("@ss.hasPermi('business:leaves:leaveStatistics')")
    @GetMapping(value = "/leave_statistics")
    public TableDataInfo leaveStatistics(leaveStatisticsDTO leaveStatisticsDTO) {
        if (leaveStatisticsDTO.getBeginDate() != null || leaveStatisticsDTO.getEndingDate() != null) {
            // 设置开始时间和结束时间
            String formattedBeginDate = DateTimeUtil.formatDateTime( leaveStatisticsDTO.getBeginDate(), true );
            String formattedEndDate = DateTimeUtil.formatDateTime( leaveStatisticsDTO.getEndingDate(), false );
            leaveStatisticsDTO.setBeginDate( formattedBeginDate );
            leaveStatisticsDTO.setEndingDate( formattedEndDate );
        }
        SysUser user = getLoginUser().getUser();
        if (!user.isAdmin()) {
            if (leaveStatisticsDTO.getSchoolId()==null) {
                leaveStatisticsDTO.setSchoolId( user.getSchoolId() );
            }
        }
        startPage();
        List<leaveStatisticsVO> leaveStatisticsVO = wsdLeavesService.leaveStatistics(leaveStatisticsDTO);
        return getDataTable(leaveStatisticsVO);
        //return AjaxResult.success(leaveStatisticsVO);
    }

    /**
     * 请假信息
     */
    @PreAuthorize("@ss.hasPermi('business:leaves:LeaveSummary')")
    @GetMapping(value = "/LeaveSummary")
    public AjaxResult LeaveSummary(LeaveSummaryDTO leaveSummaryDTO) {
        SysUser user = getLoginUser().getUser();
        Long schoolId = user.getSchoolId();
        leaveSummaryDTO.setSchoolId(schoolId.toString());
       List<LeaveSummaryVO>  leaveSummaryVOS = wsdLeavesService.LeaveSummary(leaveSummaryDTO);
       return AjaxResult.success(leaveSummaryVOS);
    }

    /**
     * 获取范围(当天, 本周, 本月, 本年)请假数量
     */
    @PreAuthorize("@ss.hasPermi('business:leaves:LeaveStatisticsProvider')")
    @GetMapping(value = "/LeaveStatisticsProvider")
    @Anonymous
    public AjaxResult LeaveStatisticsProvider() {
        SysUser user = getLoginUser().getUser();
        Long schoolId = user.getSchoolId();
        // 计算时间范围
        LocalDate today = LocalDate.now();  // 今天的日期
        LocalDate startOfWeek = today.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));  // 本周的开始日期（周一）
        LocalDate endOfWeek = today.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));  // 本周的结束日期（周日）
        LocalDate startOfMonth = today.with(TemporalAdjusters.firstDayOfMonth());  // 本月的开始日期
        LocalDate endOfMonth = today.with(TemporalAdjusters.lastDayOfMonth());  // 本月的结束日期

        // 执行查询并输出结果
        List<Map<String, Object>> results = wsdLeavesService.queryLeaveCounts(today, startOfWeek, endOfWeek, startOfMonth, endOfMonth, schoolId);
        results.forEach(System.out::println);  // 打印查询结果

        // 将结果封装为Ajax响应并返回
        return AjaxResult.success(results.stream().map(result -> new LeaveStatsVO(
                (String) result.get("timeRange"),
                ((Number) result.get("leaveCount")).intValue()
        )).collect(Collectors.toList()));
    }

}
